package com.btt.pattern.singleton.register;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 注册登记式
 *
 * created by Btt on 2018/06/28
 */
public class RegisterMap {

    private RegisterMap(){}

    //线程安全，   但是在外部操作还是需要synchronized来确保其原子性， 尤其是静态的
    private static final Map<String, Object> register = new ConcurrentHashMap<>();

    /*static {
        RegisterMap registerMap =  new RegisterMap();
        register.put(RegisterMap.class.getName(), registerMap);
    }*/

    public static final RegisterMap getInstance(String name){
        if(name == null){
            name = RegisterMap.class.getName();
        }
        synchronized(register){
            if(register.get(name) == null){
                try {
                    register.put(name, RegisterMap.class.newInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return (RegisterMap) register.get(name);
    }

    public static void main(String[] args) {

        int count = 10;
        CountDownLatch latch = new CountDownLatch(count);

        for (int i = 0; i < count; i++) {

            new Thread(() -> {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                RegisterMap registerMap = RegisterMap.getInstance(null);
                System.out.println(Thread.currentThread() + "----" + System.currentTimeMillis() + ":" +registerMap);

                latch.countDown();
            }).start();


        }

        try {
            latch.await();
            System.out.println("看看谁快 ---" + Thread.currentThread());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
